package com.db.mylogging;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.Date;
import java.util.List;

public class MyLogger {

	private List<Appender> appenders = new CopyOnWriteArrayList<>();

	private Level loggerLevel = Level.DEBUG;
	private final String name;

	public MyLogger(String name) {
		this.name = name;
	}
	
	public Level getLoggerLevel() {
		return loggerLevel;
	}

	public void setLoggerLevel(Level loggerLevel) {
		this.loggerLevel = loggerLevel;
	}

	public String getName() {
		return name;
	}

	public void addAppender(Appender appender) {
		appenders.add(appender);
	}

	public void debug(String msg) {
		log(Level.DEBUG, msg);
	}

	public void error(String msg) {
		log(Level.ERROR, msg);
	}

	public void info(String msg) {
		log(Level.INFO, msg);
	}

	public void log(Level level, String msg) {
		if (level.getValue() < loggerLevel.getValue())
			return;

		String message = String.format("%tc %s%n[%s] %s", new Date(), name, level, msg);

		for (Appender appender : appenders) {
			appender.append(message);
		}
	}
	
	public void close() {
		for (Appender appender : appenders) {
			appender.close();
		}
	}
}
